package jafou.client.ui.objects;

import jafou.client.remote.JafouService;
import jafou.client.remote.JafouServiceAsync;
import jafou.client.ui.ForumWidget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;

public class NewTopicPanel extends PopupPanel {
	private ForumWidget ui;
	private TextBox nameTB;
	private Button button;
	private String forumId;
	
	private final JafouServiceAsync handler = GWT.create(JafouService.class);

	public NewTopicPanel(ForumWidget ui, String forumId) {
		super(false, true);
		this.ui = ui;
		this.forumId = forumId;
		render();
	}
	
	private AsyncCallback<String> createTopicCallback = new AsyncCallback<String> () {

		@Override
		public void onFailure(Throwable caught) {
			handleCreateOnFailure(caught);
		}

		@Override
		public void onSuccess(String result) {
			handleCreateOnSuccess(result);
		}
		
	};

	private ClickHandler topicCreateHandler = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			String title = nameTB.getValue();
			if (title == null || "".equals(title)) {
				Window.alert("name must not be empty.");
			} else {
				button.setVisible(false);
				handler.addTopic(title, forumId, createTopicCallback);
			}
		}
	};
	
	private ClickHandler cancelHandler = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			ui.handleTopicCreation(false, "");
		}
	};
	
	private void render() {
		FlowPanel main = new FlowPanel();
		main.add(new Label("create a new topic"));
		HorizontalPanel namePanel = new HorizontalPanel();
		main.add(namePanel);
		namePanel.add(new Label("topic: "));
		nameTB = new TextBox();
		namePanel.add(nameTB);
		HorizontalPanel buttonPanel = new HorizontalPanel();
		main.add(buttonPanel);
		button = new Button("create topic", topicCreateHandler);
		buttonPanel.add(button);
		buttonPanel.add(new Button("cancel", cancelHandler));
		add(main);
	}
	
	private void handleCreateOnSuccess(String id) {
		ui.handleTopicCreation(true, id);
	}
	
	private void handleCreateOnFailure(Throwable caught) {
		ui.handleTopicCreation(false, "");
	}

}

